local httparg               = require("shared.api.httparg")
local response              = require("shared.api.response")
local config                = require("config")
local tag                   = httparg.tag()
local assertion             = httparg.assertion
local httpclient            = require "shared.http.client"
local util                  = require "proxy.game.common.util"
local fill_response_header  = util.fill_response_header
local is_match_content_type = util.is_match_content_type
local get_content_decoder   = util.get_content_decoder

local cjson = require "cjson.safe"
cjson.encode_max_depth(32)
cjson.decode_max_depth(32)

local ARGS = {
  tag.body('json', 'required'),
  id = tag.json.id ('string', 'required', assertion.non_empty_string()),
}

do
  local location = config.ENV.DATAGATE_SERVICE.."/activity"
  local headers = ngx.req.get_headers()
  local query = nil
  local method = "LIST"
  do
    headers["X-Forwarded-For"] = ngx.var.proxy_add_x_forwarded_for
  end

  local rmvLowKey = "x-http-method-override"
  local rmvKey2 = "accept-encoding"
  for k,v in pairs(headers) do
    local low = string.lower(k)
    if low == rmvLowKey or low == rmvKey2 then
      headers[k] = nil
    end
  end


  local bodyMap = {}
        bodyMap.id = ARGS.id
  local requestData = cjson.encode(bodyMap)

  local resp, err = httpclient.new()
    :uri(location)
    :headers(headers)
    :query(query)
    :body(requestData)
    :send(method, 2000, nil)

  if err or (not resp) then
    ngx.status = 500
    ngx.say(err)
    ngx.exit(ngx.OK)
  end

  if not resp.body
        or not resp.headers
        or resp.status ~= 200
        or not is_match_content_type(resp, 'application/json') then
      
      ngx.status = resp.status
      fill_response_header(resp.headers)
      ngx.say(resp.body)
      ngx.exit(ngx.OK)
  end

  local respBody
  local contentDecoder = get_content_decoder(resp)
  if contentDecoder then
    respBody = contentDecoder.decode(resp.body)
  else
    ngx.status = 500
    ngx.say(err)
    ngx.exit(ngx.OK)
  end

  response.success(respBody)
end